package com.xgr.wonderful.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.umeng.message.proguard.bu;
import com.xgr.wonderful.R;
import com.xgr.wonderful.activity.base.BasePageActivity;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.entity.Photo;
import com.xgr.wonderful.entity.Status;
import com.xgr.wonderful.entity.User;
import com.xgr.wonderful.utils.BitmapUtils;
import com.xgr.wonderful.utils.CacheUtils;
import com.xgr.wonderful.utils.HttpProxy;
import com.xgr.wonderful.utils.LocationUtils;
import com.xgr.wonderful.utils.LogUtils;
import com.xgr.wonderful.utils.HttpProxy.IHttpRequestListener;
import com.xgr.wonderful.utils.LocalUserUtils;
import com.xgr.wonderful.utils.ToastFactory;

public class PublishStatusActivity extends BasePageActivity implements OnClickListener{
	
	private ActionBar mActionBar ;
	private TextView mContentTv ;
	private ImageView mContentImg ;
	private TextView mImageTips ;
	
	private String dateTime ;
	private String targetFilePath = null;
	
	private HttpProxy httpProxy ;
	
	private User mUser ;
	
	private boolean withImg=false ;

	@Override
	protected void setLayoutView() {
		setContentView(R.layout.activity_publish_status) ;
	}

	@Override
	protected void findViews() {
		mActionBar = (ActionBar)findViewById(R.id.actionbar_publishstatus) ;
		mContentImg = (ImageView)findViewById(R.id.publish_img) ;
		mContentTv = (TextView)findViewById(R.id.publish_text) ;
		mImageTips = (TextView)findViewById(R.id.publish_img_text) ;
		mImageTips.setVisibility(View.VISIBLE) ;
		
	}

	@Override
	protected void setupViews(Bundle bundle) {
		mActionBar.setTitle("发表状态") ;
		mActionBar.setDisplayHomeAsUpEnabled(true) ;
		mActionBar.setHomeAction(new Action() {
			@Override
			public void performAction(View view) {
				finish();
			}
			
			@Override
			public int getDrawable() {
				// TODO Auto-generated method stub
				return R.drawable.weix_logo_blank;
			}
		}) ;
		mActionBar.addAction(new Action() {
			
			@Override
			public void performAction(View view) {
				publishWithOrNotImage() ;
			}
			
			@Override
			public int getDrawable() {
				// TODO Auto-generated method stub
				//return R.drawable.ic_action_send_now;
				return R.drawable.ic_ok; 
			}
		}) ;
		
		//初始化工作
		//LocationUtils.getInstance().doLocate();
		httpProxy = new HttpProxy() ;
		mUser = LocalUserUtils.getInstance().getLocalUser() ;
	}

	@Override
	protected void setListener() {
		mContentImg.setOnClickListener(this );
	}

	/**
	 * 得到存放 照片的文件，一定要在dateTime已经初始化后用.
	 * 不用引用名字，上传时可以直接由这个得到图片文件
	 * @return
	 */
	private File  getImgFile (){
		File  f = new File(CacheUtils.getCacheDirectory(mContext, 
				true, "image")+
				File.separator +
				"pic_"+dateTime+".jpg") ;
		if (! f.exists()){
			try {
				f.createNewFile() ;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return f  ;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.publish_img:
			Date date = new Date(System.currentTimeMillis()) ;
			SimpleDateFormat dateFormat = new SimpleDateFormat(
		            "'IMG'_yyyyMMdd_HHmmss");
			dateTime = dateFormat.format(date)+"" ; //确定dateTime 
			BitmapUtils.showGetImgeDialog(this , getImgFile()) ;
			break;
		default:
			break;
		}
	}
	/**
	 * 先查看 是否选择了图片,发表最后都落实在了publishStatus()里面
	 */
	private void publishWithOrNotImage (){
		if (!withImg){
			//说明没有选择图片，文字 不可以为空
			LogUtils.i(TAG, "only words");
			String content = mContentTv.getText().toString().trim() ;
			if (content.length()<=3){
				ToastFactory.getToast(mContext, "请输入多于3个文字").show() ;
				return ;
			}else {
				//只发表文字 
				publishStatus(null, content) ;
			}
		}else {
			//说明选择了图片，此时文字可以为空
			LogUtils.i(TAG, "with picture");
			publishWithImage() ;
		}
	}
	/**
	 * 先上传图片,得到url ，再发表状态
	 */
	private void publishWithImage (){
		if (targetFilePath== null) {
			//这个问题应该不存在
			//ToastFactory.getToast(mContext, "没有选择图片").show() ;
			return ;
		}
		File f = new File(targetFilePath) ;
		
		httpProxy.uploadFile(f, new IHttpRequestListener() {
			
			@Override
			public void OnHttpRequestSuccessful(String result, int errCode) {
				Photo photo = null ;
				List<Photo>  photoList = new ArrayList<Photo>() ;
				if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS){
					try {
						photo = new Gson().fromJson(result, Photo.class) ;
						photoList.add(photo) ;
					} catch (Exception e) {
						e.printStackTrace() ;
					}
					if (photoList!= null && photoList.size()!= 0){
						showProgressDialog("上传图片成功", false) ;
						publishStatus(photoList, mContentTv.getText().toString().trim()) ;
					}
				}else if (errCode == Constant.ERR_HTTP_REQUEST_FAILURE) {
					LogUtils.i(TAG, "photo upload fial") ;
					cancelProgressDialog() ;
					ToastFactory.getToast(mContext, "上传图片失败").show() ;
				}
				
			}
			
			@Override
			public void OnHttpRequestStart() {
				showProgressDialog("正在上传图片...", true) ;
			}
			
			@Override
			public void OnHttpRequestFailure(String info) {
				LogUtils.i(TAG, "photo upload fial") ;
				cancelProgressDialog() ;
				ToastFactory.getToast(mContext, "上传图片失败").show() ;
			}
		}) ;
	}
	/**
	 * 可以发只发表文字 
	 * @param photoList can be null 
	 * @param content
	 */
	private void publishStatus (List<Photo> photoList , String content ){
		Double lat = sputil.getLatestLocation().getLatitude();//LocationUtils.getInstance().getLatitude() ;
		Double lng = sputil.getLatestLocation().getLongtitude(); //LocationUtils.getInstance().getLongtitude() ;
		Status status = new Status(mUser.getID(), photoList, content, lat, lng) ;
		
		String statusJson = new Gson().toJson(status) ;
		
		httpProxy.publishStatus(statusJson, new IHttpRequestListener() {
			
			@Override
			public void OnHttpRequestSuccessful(String result, int errCode) {
				if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS){
					cancelProgressDialog() ;
					Status status = null ;
					try {
						status = new Gson().fromJson(result, Status.class) ;
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace() ;
					}
					if (status!= null){
						ToastFactory.getToast(mContext, "发表成功").show();
						Intent resIntent= new Intent() ;
						resIntent.putExtra(Constant.STATUS_FROM_SERVER, status) ;
						setResult(RESULT_OK, resIntent); //不能是resIntent 
						finish() ; //返回成功后应该进行一次刷新,setResult只有在finish后才有作用
					}
				
				}else if (errCode == Constant.ERR_HTTP_REQUEST_FAILURE) {
					cancelProgressDialog() ;
					ToastFactory.getToast(mContext, "发表失败").show() ;
				}
			}
			
			@Override
			public void OnHttpRequestStart() {
				showProgressDialog("正在发表中", false) ;
			}
			
			@Override
			public void OnHttpRequestFailure(String info) {
				cancelProgressDialog() ;
				ToastFactory.getToast(mContext, "发表失败").show() ;
			}
		}) ;
	}
	/**
	 * 流程应该是:
	 * 先从album得到图片uri,zoom后保存到getImageFile中，再将file根据filepath压缩
	 * 成bitmap后读取到内存中，再将bitmap压缩成file(可设置file大小)，然后可以上传 file 
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK){
			switch (requestCode) {
			case BitmapUtils.CAMERA_REQUEST:
				File f = getImgFile() ;//得到存放图片的地方 
				LogUtils.i(TAG, "camera");
				handleImage(f) ;
				break;
			case BitmapUtils.ALBUM_REQUESRT:
				if (data == null){
					return ;
				}
				String fPath =BitmapUtils.uriToPath(data.getData(), mContext) ;
				File f1 = new File(fPath) ;
				handleImage(f1) ;
				break ;
			default:
				break;
			}
		}
	}
	/**
	 * 先将图片压缩成bitmap并读取到内存中
	 * 再将bitmap压缩成file(<80k)，文件地址为getImageFile()
	 * 最后可以上传到服务器
	 * @param f
	 */
	private void handleImage(File f ){
		if (!f.exists()|| f.length()==0){
			ToastFactory.getToast(mContext, "请选择图片").show();
			return ;
		}
		//将file根据filepath压缩 成bitmap后读取到内存中
		Bitmap bitmap = BitmapUtils.compressBitmapFromFile(
				f.getAbsolutePath()) ;
		if (bitmap != null){
			//再将bitmap压缩成file(可设置file大小)，然后可以上传 file到服务器
			targetFilePath = BitmapUtils.compressBmpAndSaveToFile(mContext,
					bitmap, getImgFile().getName(), 80) ;
			mContentImg.setImageBitmap(bitmap) ;
			mImageTips.setVisibility(View.INVISIBLE) ;
			withImg= true ;
		}
	}
	
	

}




 